import {defineStore} from 'pinia'
import Cookies from 'js-cookie'
import {ref} from "vue";

// You can then use sessionStorage, localStorage or any custom storage object.
// In this example we create a storage that uses the js-cookie npm module
// to get and set the user's access token into a cookie.
const remember = ref(false)
const cookiesStorage  = {
    setItem (key, state) {
        console.log(`setItem ${key} -- ${state}`)
        //JSON字符串对象转换成JS对象
        let myState = JSON.parse(state)
        if (remember.value) {
            return Cookies.set(key, myState.token, { expires: 7 })
        } else {
            return Cookies.set(key, myState.token)
        }
    },
    getItem (key) {
        return JSON.stringify({
            token: Cookies.get(key)
        })
    }
}

export const useTokenStore = defineStore('token', {
    //存数据地方
    state() {
        return {
            token: ''
        }
    },
    //actions里面放一个一个方法
    actions: {
        setToken(newToken, rem) {
            //localStorage.setItem('study1', 'java')
            //sessionStorage.setItem('study2', 'ui')
            this.token = newToken
            remember.value = rem
        },
        removeToken() {
            this.token = ''
        }
    },
    persist: {
        enabled: true, // 开启缓存  默认会存储在本地localstorage
        storage: cookiesStorage
    }
})